package handlers

import (
	"book/models"
	"book/pkg"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"math"
	"net/http"
	"strconv"
)

type MsgData struct {
	Sum   int `json:"sum"`
	Up    int `json:"up"`
	Down  int `json:"down"`
	Books []models.Book
}

func UserLogin(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		username := c.PostForm("username")
		password := c.PostForm("password")
		var user models.User
		err := db.Where("username=?", username).First(&user).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "用户名不能重复",
			})
			return
		}
		if user.Password != pkg.Md5Str(password) {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "密码密码错误",
			})
			return

		} else {
			token, _ := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
			c.JSON(http.StatusOK, gin.H{
				"code":  200,
				"msg":   "登陆成功",
				"token": token,
			})
		}
	}
}
func List(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
		size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
		offset := (page - 1) * size
		var count int64
		db.Model(&models.Book{}).Count(&count)
		sum := int(math.Ceil(float64(count) / float64(size)))
		up := page - 1
		if up < 1 {
			up = 1
		}
		down := page + 1
		if down > sum {
			down = sum
		}
		var books []models.Book
		err := db.Offset(offset).Limit(size).Find(&books).Error
		pagedata := MsgData{
			Sum:   sum,
			Up:    up,
			Down:  down,
			Books: books,
		}
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "分页查询失败",
			})
			return
		} else {
			c.JSON(http.StatusOK, gin.H{
				"code": 200,
				"msg":  "分页查询成功",
				"data": pagedata,
			})
		}
	}
}
